package org.ccay.ws.internal.impl;

import java.text.MessageFormat;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.async.AsyncMessage;
import org.ccay.async.IMessageProcessor;
import org.ccay.async.IMessageSender;
import org.ccay.core.cache.ehcache.CacheEvent;
import org.ccay.core.cache.ehcache.ICacheEventHandler;
import org.ccay.core.exception.ApplicationException;
import org.ccay.ws.service.IClusterInvokeService;

/**
 * 集群缓存事件处理器，用于集群缓存同步
 */
@Named
public class ClusterCacheEventHandler implements ICacheEventHandler, IMessageProcessor{
	@Inject
	private IMessageSender messageSender;
	
	/* (non-Javadoc)
	 * @see www.ccay.org.ccay.core.cache.ehcache.ICacheEventHandler#execute(java.lang.Object, www.ccay.org.ccay.core.cache.ehcache.CacheEvent)
	 */
	public void execute(Object sender, CacheEvent args) throws ApplicationException {
		AsyncMessage message = new AsyncMessage("CacheSync");
		message.setContent(args);
		//使用异步框架处理此事件
		messageSender.send(message);
	}
	
	@Inject
	private IClusterInvokeService cluster; 
	/* (non-Javadoc)
	 * @see www.ccay.org.ccay.async.IMessageProcessor#process(www.ccay.org.ccay.async.AsyncMessage)
	 */
	public void process(AsyncMessage message) throws ApplicationException {
		CacheEvent e = (CacheEvent)message.getContent();		
		String query = MessageFormat.format("type={0}&name={1}&key={2}&distributed={3}", e.getType(),e.getCacheName(),e.getKey(), e.isDistributed());		
		cluster.invoke("servlet/cache", query);
	}

}
